package org.example.project.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.bean.User;
import org.example.config.JwtConfig;
import org.example.handler.UserNotFoundException;
import org.example.handler.UserSaveException;
import org.example.mapper.UserMapper;
import org.example.project.bookstore.service.UserService;
import org.example.util.JsonResult;
import org.example.util.MD5Util;
import org.example.util.ResultTool;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.management.Query;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Auther:Liu
 * @Testname:UserServiceImpl
 * @Date:2025/8/18 11:12
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public static final String LOGIN_PREFIX = "user_login_";


    /**
     * 登陆方法
     *
     * @param user
     * @return
     */
    @Override
    public JsonResult login(User user) {
        User loginUser = findUserName(user.getUsername());
        if (loginUser == null) {
            throw new UserNotFoundException("用户账号不存在");
        }
        if (!Objects.equals(MD5Util.encryptMD5(user.getPassword()),loginUser.getPassword())){
            throw new UserNotFoundException("用户密码不正确");
        }
        String jwtToken = JwtConfig.getJwtToken(loginUser);
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.set(LOGIN_PREFIX+loginUser.getId(),jwtToken,1, TimeUnit.DAYS);
        return ResultTool.success(jwtToken);
    }

    /**
     * 获取用户姓名&&判断令牌是否存在
     * @param token
     * @return
     */
    @Override
    public JsonResult getUserName(String token) {
        boolean b = JwtConfig.checkToken(token);
        if (!b) {
            throw new UserNotFoundException("令牌不存在");
        }
        Claims claims = JwtConfig.parseJWT(token);
        Object userId = claims.get("id");
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String s = ops.get(LOGIN_PREFIX + userId);
        if (s == null) {
            throw new UserNotFoundException("令牌数据不一致");
        }
        if (!Objects.equals(s, token)) {
            throw new UserNotFoundException("令牌数据不一致");
        }
        return ResultTool.success(claims.get("name"));
    }

    /**
     * 退出登录
     * @param token
     * @return
     */
    @Override
    public JsonResult outLogin(String token) {
        boolean b = JwtConfig.checkToken(token);
        if (!b) {
            throw new UserNotFoundException("令牌不存在");
        }
        Claims claims = JwtConfig.parseJWT(token);
        Object userId = claims.get("id");
       stringRedisTemplate.delete(LOGIN_PREFIX + userId);
       return ResultTool.success("success");
    }

    /**
     * 添加用户信息
     *
     * @param user
     * @return
     */
    @CacheEvict(cacheNames = "UserList",key = "#user.id",allEntries = true)
    public JsonResult saveUser(User user) {
        String s = MD5Util.encryptMD5(user.getPassword());
        user.setPassword(s);
        boolean b = save(user);
        if (!b) {
            throw new UserSaveException("注册账号失败");
        } else {
            return ResultTool.success("注册成功");
        }
    }

    /**
     * 查询用户姓名
     * @param username
     * @return
     */
    public User findUserName(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        wrapper.eq("status", 1);
        return getOne(wrapper);
    }
}
